package com.furnitur.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.furnitur.common.utils.SecurityUtils;
import com.furnitur.core.entity.order.Order;
import com.furnitur.core.entity.user.User;
import com.furnitur.core.mapper.order.OrderMapper;
import com.furnitur.core.mapper.user.UserMapper;
import com.furnitur.core.service.StatisticsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class StatisticsServiceImpl implements StatisticsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Override
    public Map<String, Object> getStatistics() {
        Map<String, Object> result = new HashMap<>();
        
        // 获取当前用户
        User currentUser = SecurityUtils.getCurrentUser();
        
        if (currentUser.getRoleId() == 1) {
            // 管理员统计
            // 1. 用户总数
            result.put("userCount", userMapper.selectCount(new QueryWrapper<User>()
                    .eq("role_id", 3))); // 普通用户

            // 2. 商家总数
            result.put("merchantCount", userMapper.selectCount(new QueryWrapper<User>()
                    .eq("role_id", 2))); // 商家用户

            // 3. 订单总数
            result.put("totalOrderCount", orderMapper.selectCount(null));

        } else if (currentUser.getRoleId() == 2) {
            // 商家统计
            Long merchantId = currentUser.getId();
            Date thirtyDaysAgo = Date.from(LocalDateTime.now().minusDays(30)
                    .atZone(ZoneId.systemDefault()).toInstant());

            // 1. 近30天订单数
            result.put("orderCount", orderMapper.selectCount(new QueryWrapper<Order>()
                    .eq("merchant_id", merchantId)
                    .ge("created_at", thirtyDaysAgo)));

            // 2. 近30天销售总额
            List<Order> orders = orderMapper.selectList(new QueryWrapper<Order>()
                    .eq("merchant_id", merchantId)
                    .ge("created_at", thirtyDaysAgo));

            BigDecimal totalAmount = orders.stream()
                    .map(Order::getTotalAmount)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            result.put("totalAmount", totalAmount);
        }
        
        return result;
    }
}
